package class01;

import java.util.Arrays;

/**
 * 在有序数组中，找到大于等于某个数最右侧的位置
 *
 * <a href="https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/">34. 在排序数组中查找元素的第一个和最后一个位置</a>
 */
public class Code05_BSNearLeft {
    public static int nearestIndex(int[] arr, int number) {
        int L = 0, R = arr.length - 1, result = -1;
        while (L <= R) {  // 至少一个数的时候
            int M = L + ((R - L) >> 1);
            if (number <= arr[M]) {
                result = M;
                R = M - 1;
            } else {
                L = M + 1;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] arr = new int[20];
        for (int i = 0; i < arr.length; ++i) {
            arr[i] = (int) (Math.random() * (10 - 1) + 1);
        }
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        System.out.println(nearestIndex(arr, 2));
    }
}
